package com.bootdo.system.controller;

import com.bootdo.common.utils.StringUtils;
import com.bootdo.system.domain.OrderDO;
import com.bootdo.system.service.OrderService;
import com.bootdo.system.wechatUtil.WeChatPay;
import com.bootdo.system.wechatUtil.XMLUtil;
import com.bootdo.system.wechatUtil.ZxingUtil;
import org.jdom2.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;


@RequestMapping("/wechat")
@Controller
public class WechatController {

    @Autowired
    private OrderService orderService;

    @ResponseBody
    @RequestMapping("/weixinPay")
    public String weixinPay(HttpServletRequest request, OrderDO orderDO, RedirectAttributes attr){
        //请求IP地址
        String ip = request.getRemoteAddr();
        //发起支付
        WeChatPay weChatPay = new WeChatPay();
        String orderNo=getOrderIdByTime();
        orderDO.setOrderNo(orderNo);
        //微信
        orderDO.setPayType("2");
        //还未支付
        orderDO.setStatus("3");
        orderService.save(orderDO);

        /**
         * 调用微信支付
         * order.getOrderNo() 订单号
         *  price 订单价格精度转换后的价格   order.getPrice()  订单价格，因为微信是分为单位 所以这里要乘以100   关于支付精度转换，可以查看 https://www.cnblogs.com/pxblog/p/13186037.html
         */
        Map map = weChatPay.getPaymentMapCode(orderNo,orderDO.getPayMoney(), "微信支付", ip);
        String return_code = String.valueOf(map.get("return_code"));
        if (return_code.equals("SUCCESS")) {
            //微信调用成功 code_url是支付的链接
            request.getSession().setAttribute("code_url", map.get("code_url") + "");
            attr.addAttribute("order", orderDO);
            return "redirect:/get_qr_code";
            //跳转到支付页面
        } else {
            //微信支付调取失败!
            return "";
        }
    }

    public static String getOrderIdByTime() {
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate=sdf.format(new Date());
        String result="";
        Random random=new Random();
        for(int i=0;i<3;i++){
            result+=random.nextInt(10);
        }
        return newDate+result;
    }


    @GetMapping("/get_qr_code")
    public String getQrCode(HttpServletRequest request, HttpServletResponse response, Model model, OrderDO orderDO) throws Exception {
        //从session中获取前面放在code_url地址

        String content = request.getSession().getAttribute("code_url") + "";
        String base64Str = ZxingUtil.enCode("https://ask.csdn.net/questions/695053");
        System.out.printf(base64Str);
        model.addAttribute("base64Str", base64Str);
        model.addAttribute("order", orderDO);
        return  "shibanhe/online_code";
        //return  "shibanhe/success_pay";
        //二维码图片中间logo
       /* String imgPath = "";
        Boolean needCompress = true;
        //通过调用我们的写的工具类，拿到图片流
        ByteArrayOutputStream out = QRCodeUtil.encodeIO(content, imgPath, needCompress);
        //定义返回参数
        response.setCharacterEncoding("UTF-8");
        response.setContentType("image/jpeg;charset=UTF-8");
        response.setContentLength(out.size());
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(out.toByteArray());
        outputStream.flush();
        outputStream.close();*/
    }



    /**
     * 微信支付通知
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/wechart_notice")
    public String wechartNotice(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        String result = "";
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            result = new String(outSteam.toByteArray(), "utf-8");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //判断返回报文是否为空
        if (StringUtils.isNotBlank(result)) {
            try {
                Map<String, String> map = XMLUtil.doXMLParse(result);
                //获取商家订单编号 对应orderNo
                String orderNo = map.get("out_trade_no");
                //获取微信支付订单号
                String transaction_id = map.get("transaction_id");

                OrderDO order = orderService.findByOrderNo(orderNo);
                //判断支付是否成功
                if ("SUCCESS".equals(map.get("result_code"))) {
                    //支付成功，这里之所以加了一个判断，是因为这个回调可能会有多次，所以我们只有当订单状态时未支付成功的情况下，才执行下面操作
                    if (!"1".equals(order.getStatus())) {
                        //当微信支付成功后，把订单支付状态改为已支付
                        order.setStatus("1");
                    }
                    //处理业务逻辑
                } else {
                    //支付失败
                    order.setStatus("2");
                }
                //更新数据库订单状态
                orderService.update(order);
            } catch (JDOMException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return WeChatPay.getSuccessXml();
    }

}
